package com.lt.utils.Activity;


import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import java.util.List;

/**
 * Fragment 相关管理
 * @author LiuTong
 *
 */
public class FragmentUtils {
    private FragmentActivity activity;
    private FragmentManager fragmentManager;
    private FragmentTransaction fragmentTransaction;

    public FragmentUtils(AppCompatActivity activity){
        this.activity = activity;
        init();
    }

    private void init() {
        fragmentManager = activity.getSupportFragmentManager();
        fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.commit();
    }

    private void addFragment(int id, Fragment fragment){
        addFragment(id,fragment,fragment.getClass().getSimpleName());
    }
    private void addFragment( int id, Fragment fm, String tag){
        fragmentTransaction
                .add(id,fm, tag)
                .setReorderingAllowed(true);
    }

    public void replaceFragment(int id,Fragment fragment){
        if(!getFragment().contains(fragment)){
            addFragment(id,fragment);
        }
        fragmentTransaction.replace(id,fragment);
        fragmentTransaction.show(fragment);
    }

    public List<Fragment> getFragment(){
       return fragmentManager.getFragments();
    }

}
